import '@/assets/css/MainView.css'

import { ref, onMounted } from 'vue'
import { projectAPI } from '../api/projectApi'
import { getCookie } from '@/utils/cookie'
export const loading = ref(true)
export const projectList = ref([])
export const projectCount = ref(0)

export const fetchProjectList = async () => {
  try {
    loading.value = true
    const data = await projectAPI.getProjects() // 将数据赋值给响应式变量
    // console.log('获取项目列表成功:', data)
    if (data.length > 0) {
      projectList.value = data
      projectCount.value = data.length
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 将 onMounted 移到函数外部
// 导出一个初始化函数
export const initMainView = () => {
  onMounted(() => {
    fetchProjectList()
  })
}

export default {
  name: 'MainView',
  setup() {
    initMainView()

    const days = ref(0)

    onMounted(() => {
      const userCookie = getCookie('user')
      if (userCookie) {
        try {
          const user = JSON.parse(userCookie)
          const createdAt = new Date(user.createdAt)
          const today = new Date()

          const timeDiff = today.getTime() - createdAt.getTime()
          const daysDiff = Math.floor(timeDiff / (1000 * 3600 * 24))

          days.value = Math.max(daysDiff, 0)
        } catch (error) {
          console.error('解析用户信息失败:', error)
          days.value = 0
        }
      }
    })

    return {
      days,
      projectList,
      projectCount,
      loading,
    }
  },

  mounted() {
    document.title = 'Main'
  },
}
